<?php


namespace app\common\controller;

use think\Db;

/**
 * USPS接口
 * Class Usps
 * @package app\common\controller
 */
class Usps
{
//    private $url = "https://secure.shippingapis.com/ShippingAPI.dll";
    private $url = "http://production.shippingapis.com/shippingAPI.dll";//生产
//    private $usps_user_id = '337HERFE6833';//账号
//    private $shipper_zip_origination = 92821;//发货地邮编

    private $usps_user_id = '';//账号
    private $shipper_zip_origination = '';//发货地邮编

    /**
     * 初始化参数
     */
    public function __construct()
    {
        //从后台配置中获取账号信息
        $config = Db::name('shipping_method')->where('id',2)->value('config');
        $config = json_decode($config,true);
        $this->usps_user_id = $config['usps_user_id'];
        $this->shipper_zip_origination = $config['shipper_zip_origination'];
    }

    public function send_host($service,$xml){
        $request = $this->url . "?API=" . $service . "&XML=" . $xml;
        // send the POST values to USPS
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$request);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_HTTPGET, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // parameters to post
        $result = curl_exec($ch);
        curl_close($ch);
        $response = json_decode(json_encode(simplexml_load_string($result)), true);
        return $response;
    }
    /**
     * 获取运费
     */
    public function get_usps_freight($postalCode,$countryCode,$cart,$service){
        if(empty($postalCode)){
            return ['code'=>10,'msg'=>'收货地邮编不能为空'];
        }
        if(empty($cart)){
            return ['code'=>10,'msg'=>'商品为空'];
        }
        if(empty($service)){
            return ['code'=>10,'msg'=>'请选择运输类型'];
        }

        //·        PRIORITY
        //·        PRIORITY COMMERCIAL
        //·        PRIORITY CPP
        //·        RETAIL GROUND
        $str_xml = '';
        $j = 0;
        foreach ($cart as $k=>$v){
            for ($i=1;$i<=$v['total_num'];$i++){
                $str_xml .= '<Package ID="'.$j.'">
<Service>RETAIL GROUND</Service>
<ZipOrigination>'.$this->shipper_zip_origination.'</ZipOrigination>
<ZipDestination>'.$postalCode.'</ZipDestination>
<Pounds>'.$v['weight'].'</Pounds>
<Ounces>0</Ounces>
<Container></Container>
<Width>'.ceil($v['wide']).'</Width>
<Length>'.ceil($v['long']).'</Length>
<Height>'.ceil($v['high']).'</Height>
<Girth></Girth>
<Machinable>TRUE</Machinable>
</Package>';
                $j++;
            }
        }

        $xml_old = '<RateV4Request USERID="'.$this->usps_user_id.'">
<Revision>2</Revision>
'.$str_xml.'
</RateV4Request>';
//        halt($xml_old);
        $xml = rawurlencode($xml_old);
        $response = $this->send_host('RateV4',$xml);
//        dump($response);
        if(isset($response['Package'])){
            if(isset($response['Package']['Error'])){
                return ['code'=>10,'msg'=>$response['Package']['Error']['Description']];
            }
            $freight = $response['Package']['Postage']['Rate'];
//            foreach ($response['Package'] as $k=>$v){
//                $freight += $v['Postage']['Rate'];
//            }
//        halt($freight);
            return ['code'=>20,'msg'=>'查询成功','freight'=>$freight];
        }else{
            return ['code'=>10,'msg'=>$response['Description']];
        }

    }

    /**
     * 根据跟踪号获取物流详情
     */
    public function get_usps_info($trackingNumber){
//        $trackingNumber = '9405509106029500013292';
        $xml = rawurlencode("<TrackRequest USERID='".$this->usps_user_id."'><TrackID ID='".$trackingNumber."'></TrackID></TrackRequest>");
        $response = $this->send_host('TrackV2',$xml);
        halt($response);
        return ['code'=>20,'msg'=>'查询成功','data'=>$response];
    }

    /**
     * 生成物流单，并打印
     */
    public function create_ship($goods,$address){
        $all_weight = 0;
        foreach ($goods as $k=>$v){
            $goods_weight = $v['goods_weight']*$v['total_num'];
            $all_weight += $goods_weight;
        }

        $json_data = '{
  "labelResponseOptions": "URL_ONLY",
  "requestedShipment": {
    "shipper": {
      "contact": {
        "personName": "'.$this->shipper_person_name.'",
        "phoneNumber": '.$this->shipper_phone_number.'
      },
      "address": {
        "streetLines": [
          "'.$this->shipper_street_lines.'"
        ],
        "city": "'.$this->shipper_city.'",
        "stateOrProvinceCode": "'.$this->shipper_state_or_province_code.'",
        "postalCode": '.$this->shipper_postal_code.',
        "countryCode": "'.$this->shipper_country_code.'"
      }
    },
    "recipients": [
      {
        "contact": {
          "personName": "'.$address['first_name'].' '.$address['last_name'].'",
          "phoneNumber": '.$address['phone_number'].',
        },
        "address": {
          "streetLines": [
            "'.$address['detail'].'"
          ],
          "city": "'.$address['city'].'",
          "stateOrProvinceCode": "'.$address['state_code'].'",
          "postalCode": '.$address['postal_code'].',
          "countryCode": "'.$address['country_code'].'"
        }
      }
    ],
    "shipDatestamp": "'.date('Y-m-d H:i:s').'",
    "serviceType": "'.$address['service'].'",
    "packagingType": "YOUR_PACKAGING",
    "pickupType": "USE_SCHEDULED_PICKUP",
    "blockInsightVisibility": false,
    "shippingChargesPayment": {
      "paymentType": "SENDER"
    },
    "shipmentSpecialServices": {
      "specialServiceTypes": [
        "RETURN_SHIPMENT"
      ],
      "returnShipmentDetail": {
        "returnType": "PRINT_RETURN_LABEL"
      }
    },
    "labelSpecification": {
      "imageType": "PDF",
      "labelStockType": "PAPER_85X11_TOP_HALF_LABEL"
    },
    "requestedPackageLineItems": [
      {
        "weight": {
          "value": '.$all_weight.',
          "units": "LB"
        }
      }
    ]
  },
  "accountNumber": {
    "value": "'.$this->account_number.'"
  }
}';
//        echo $json_data;exit;
        $response = $this->send_host('/ship/v1/shipments',$json_data);
        halt($response);
        if($response['code'] == 10){
            return $response;
        }
        $list = $response['data']['output']['completeTrackResults'][0]['trackResults'][0]['scanEvents'];
        return ['code'=>20,'msg'=>'查询成功','data'=>$list];
    }

}